package com.wude.guild.adapter;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.wude.bean.AppInfo;
import com.wude.guild.holder.HomeGameHolder;
import com.wude.guild.manager.DownloadManager;
import com.wude.guild.manager.DownloadObserver;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by LeBron on 2016/10/8.
 * home页面游戏列表
 */

public class HomeGameAdapter extends BaseAdapter implements DownloadObserver {
    private List<HomeGameHolder> mHolders = new LinkedList<HomeGameHolder>();
    private List<AppInfo> giftBeanList;

    private Activity context;

    public HomeGameAdapter(Activity context) {
        this.context = context;
    }

    public void setData(List<AppInfo> giftBeanList) {
        this.giftBeanList = giftBeanList;
    }

    @Override
    public int getCount() {
        return giftBeanList == null ? 0 : giftBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return giftBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HomeGameHolder holder = null;
        if (convertView == null) {
            holder = new HomeGameHolder();
            mHolders.add(holder);
        } else {
            holder = (HomeGameHolder) convertView.getTag();
        }
        AppInfo giftBean = giftBeanList.get(position);
        holder.setData(giftBean, position, context);
        return holder.getContentView();
    }

    @Override
    public void onDownloadStateChanged(DownloadManager manager, AppInfo info) {

        ListIterator<HomeGameHolder> iterator = mHolders.listIterator();
        while (iterator.hasNext()) {
            HomeGameHolder holder = iterator.next();
            holder.Refresh(info);
        }
    }

    public void start() {
        DownloadManager.getInstance().addObserver(this);
    }

    public void delete() {
        DownloadManager.getInstance().deleteObserver(this);
    }

    public void State() {
        ListIterator<HomeGameHolder> iterator = mHolders.listIterator();
        while (iterator.hasNext()) {
            HomeGameHolder holder = iterator.next();
            holder.an();
        }
    }
}
